package serversidepkg;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backendpkg.DataSource;

/**
 * Servlet implementation class Logout
 */
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
			response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
			response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
			response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
			
			//Get writer to print logout page
			PrintWriter pw = response.getWriter();
			
			HttpSession session = request.getSession();
			
			//Get user to logout from session
            String user = (String) session.getAttribute("username");

			//Get connection to DB
	        DataSource datasource = new DataSource();
	        Connection conn = datasource.getConnection();
	        
	        PreparedStatement statement;
	        
	        //Set User Offline
	        String setOffline = "UPDATE User SET last_online=NULL WHERE username=?";
	        
			statement = (PreparedStatement) conn.prepareStatement(setOffline);
			statement.setString(1, user);
			statement.executeUpdate();
			
			//Delete all message sent or received by the user
			String delMsg = "DELETE FROM Message WHERE Message.chat_id IN (SELECT chat_id FROM Chat"+
							" WHERE user1=? OR user2=?)";
			statement = conn.prepareCall(delMsg);
			statement.setString(1,user);
			statement.setString(2,user);
			statement.executeUpdate();
			
			//Delete all chat request sent
			String delincom = "DELETE FROM Incoming WHERE sender=?";
			statement = conn.prepareCall(delincom);
			statement.setString(1,user);
			statement.executeUpdate();
			
			//Refuse all pending chat requests
			String updinc = "UPDATE Incoming SET accepted=false WHERE receiver=?";
			statement = conn.prepareCall(updinc);
			statement.setString(1,user);
			statement.executeUpdate();
			
			//Delete all chat involving user
			String delchat = "DELETE FROM Chat WHERE user1=? OR user2=?";
			statement = conn.prepareCall(delchat);
			statement.setString(1,user);
			statement.setString(2,user);
			statement.executeUpdate();
			
			conn.close();
			
			//Remove attribute username and invalidate session
			session.removeAttribute("username");
			session.invalidate();
			
			//Print logout page
			pw.println("<html><head>");
			pw.println("<script language=\"JavaScript\">");
			pw.println("var time = null");
			pw.println("function move() { window.location = 'login.jsp' } </script>");
			pw.println("<body onload=\"timer=setTimeout('move()',2000)\">"+
			"Logout executed</body></html>");
            
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        
	}

}
